<?php

namespace App\Model\Admin;
use App\Model\BaseModel;
use App\Utility\Pagination;
class Config extends BaseModel
{
    protected $table = 'osc_config';

    function get_db_config(){
        $data = $this->db->where('status',1)->get($this->table);
		
		$config=null;
		foreach ($data as $k => $v) {
			$config[trim($v['name'])]=$v['value'];
		}
		
		return $config;
    }
	
	function get_config_page($param){			
	
		$page=!isset($param['page']) ? 0 : $param['page'];
		
		if($page!=0){			
			$get_page=$page-1;
		}else{
			$get_page=0;
		}
		
		$page_size=DbConfig('page_num');
		
		$sql='select * from '.$this->table.' where id>0 ';
		
		if(isset($param['name'])){			
			$sql.=" and name like '%".$param['name']."%'";	
		}
		if(isset($param['module'])){			
			$sql.=" and module='".$param['module']."'";			
		}
		
		$sql.=" order by id desc ";		
		
		$total=count($this->db->rawQuery($sql));
		
		$sql.=" limit ".$get_page*$page_size.','.$page_size;
		
		$list=null;
		
		$list = $this->db->rawQuery($sql);
		 
		$pagination = new Pagination();
		$pagination->total = $total;
		$pagination->page = $page;
		$pagination->limit = $page_size;
		$pagination->param = $param;
		$pagination->url ='/admin/config/index';
		
		$render = $pagination->render();		 
		 
		return ['list'=>$list,'page'=>$render,'total'=>$total];
		 
	}
	
	function get_by_id($id){
        $data = $this->db->where('id',$id)->getOne($this->table);
        return empty($data) ? null : $data;
    }
	
	function add($data){
		
		if($id= $this->db->insert($this->table,$data)){
			return $id;
		}else{
			return ['error'=>$this->db->getLastError()];
		}
	}
	function edit($data){
	
		$id=$data['id'];
		unset($data['id']);
		
		return $this->db->where('id',$id)->update($this->table,$data);
		
	}
	//删除单个元素
	 function delete($id){
        return $this->db->where('id',$id)->delete($this->table);
    }
}